package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.ShoppingCartListAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.network.task.ModifyShoppingCartTask;
import com.zw.yzk.kabu.internal.component.DaggerShoppingCartComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.DeleteShoppingCartModule;
import com.zw.yzk.kabu.internal.module.GetShoppingCartModule;
import com.zw.yzk.kabu.internal.module.ModifyShoppingCartModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.model.ShoppingCartGoodsModel;
import com.zw.yzk.kabu.model.ShoppingCartModel;
import com.zw.yzk.kabu.model.SubmitGoods;
import com.zw.yzk.kabu.model.SubmitOrder;
import com.zw.yzk.kabu.presenter.ShoppingCartPresenter;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.view.view.ShoppingCartView;
import com.zw.yzk.kabu.view.widget.EditShoppingCartDialog;


import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by zhanwei on 2017/2/7.
 */

public class ShoppingCartActivity extends BaseActivity implements ShoppingCartView, ShoppingCartListAdapter.OnCoastChangedListener {

    @Bind(R.id.edit)
    TextView edit;
    @Bind(R.id.complete)
    TextView complete;
    @Bind(R.id.shopping_list)
    RecyclerView shoppingList;
    @Bind(R.id.select_all)
    CheckBox selectAll;
    @Bind(R.id.total)
    TextView total;
    @Bind(R.id.total_price)
    TextView totalPrice;
    @Bind(R.id.balance)
    TextView balance;
    @Bind(R.id.clear)
    TextView clear;
    @Bind(R.id.layout_bottom)
    View bottomLayout;
    @Bind(R.id.empty)
    View empty;

    @Inject
    ShoppingCartPresenter presenter;
    private ShoppingCartListAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_shopping_cart;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
    }

    @Override
    public void initComponent() {
        DaggerShoppingCartComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .getShoppingCartModule(new GetShoppingCartModule())
                .modifyShoppingCartModule(new ModifyShoppingCartModule())
                .deleteShoppingCartModule(new DeleteShoppingCartModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecyclerView();
//        getShoppingCart();
//        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (adapter == null || !adapter.isEditMode()) {
            getShoppingCart();
            LoadingDialogManager.getInstance().showLoadingDialog(this);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getShoppingCartSuccess(List<ShoppingCartModel> list) {
        if (adapter == null) {
            adapter = new ShoppingCartListAdapter(list);
            adapter.setOnTotalPriceChangedListener(this);
            shoppingList.setAdapter(adapter);
        } else {
            adapter.refresh(list);
        }
        hideBottomLayout(adapter.getItemCount() == 0);
    }

    @Override
    public void getShoppingCartFailed() {
        hideBottomLayout(adapter == null || adapter.getItemCount() == 0);
    }

    @Override
    public void onCoastChanged(float price) {
        String withoutFreight = getResources().getString(R.string.without_freight);
        String formatString = ResUtils.formatCurrency(this, price) + withoutFreight;
        SpannableString spanText = new SpannableString(formatString);
        spanText.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.text_12)),
                formatString.indexOf(withoutFreight), formatString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanText.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_black_regular)),
                formatString.indexOf(withoutFreight), formatString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        totalPrice.setText(spanText);

        //如果金额不等于所有商品总金额，那么就不是全选状态
        selectAll.setChecked(price == adapter.calculatTotalPrice());
    }

    @Override
    public void onEditGoods(ShoppingCartGoodsModel model) {
        new EditShoppingCartDialog.Builder(this, model.getGoodsId())
                .setImage(model.getImage())
                .setPropertyList(model)
                .setConfirmClickedListener(new EditShoppingCartDialog.OnConfirmClickedListener() {
                    @Override
                    public void onClick(int count, String skuId, String property, int shoppingCartId) {
                        List<ShoppingCartModel> models = adapter.getShoppingCartList();
                        int i = -1;
                        for (int j = 0; j < models.size(); j++) {
                            for (ShoppingCartGoodsModel g : models.get(j).getModels()) {
                                if (g.getId() == shoppingCartId) {
                                    g.setCount(count);
                                    g.setSkuId(skuId);
                                    g.setSelectedProperty(property);
                                    i = j;
                                }
                            }
                            models.get(j).setEditMode(false);
                        }
                        if (i != -1) {
                            adapter.notifyItemChanged(i);
                        }
                        modifyShoppingCart();
                    }
                })
                .build()
                .showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onEditShop(int shopId) {
        modifyShoppingCart();
    }

    @OnClick(R.id.back)
    public void cancel() {
        finish();
    }

    @OnClick(R.id.edit)
    public void enterEditMode() {
        editModeChange(true);
        if (adapter != null) {
            adapter.changeMode(true);
        }
    }

    @OnClick(R.id.complete)
    public void editComplete() {
        editModeChange(false);
        if (adapter != null) {
            adapter.changeMode(false);
            modifyShoppingCart();
        }
    }

    @OnClick(R.id.select_all_layout)
    public void selectAll() {
        if (adapter == null) {
            return;
        }
        if (selectAll.isChecked()) {
            adapter.unSelectAll();
        } else {
            adapter.selectAll();
        }
    }

    @OnClick(R.id.balance)
    public void balance() {
        int receivedId;
        try {
            receivedId = DataBaseManager.getInstance().getLoginUser().getAddress().getReceiveId();
        } catch (Exception e) {
            //如果用户没有登录，那么传入0，在用户没有登录的情况下服务器首先会返回用户没有登录的错误
            receivedId = 0;
        }

        if (adapter == null || adapter.getItemCount() == 0) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.no_selected_goods));
            return;
        }
        ArrayList<SubmitOrder> orderList = new ArrayList<>();
        for (ShoppingCartModel model : adapter.getShoppingCartList()) {
            SubmitOrder order = new SubmitOrder();
            ArrayList<SubmitGoods> goodsList = new ArrayList<>();
            if (model.getModels() == null || model.getModels().isEmpty()) {
                continue;
            }
            for (ShoppingCartGoodsModel m : model.getModels()) {
                SubmitGoods goods = new SubmitGoods();
                if (m.isSelected()) {
                    goods.setGoodsId(m.getGoodsId());
                    goods.setCount(m.getCount());
                    goods.setSkuId(m.getSkuId());
                    goods.setName(m.getGoodsName());
                    goods.setImage(m.getImage());
                    goods.setPrice(m.getPrice());
                    goods.setProperty(m.getSelectedProperty());
                    goods.setFreight(m.getFreight());
                    goods.setShoppingCardId(m.getId());

                    goodsList.add(goods);
                }
            }
            if (!goodsList.isEmpty()) {
                order.setGoodsList(goodsList);
                order.setShopId(model.getId());
                order.setReceiverInfoId(receivedId);
                order.setShopName(model.getShopName());

                orderList.add(order);
            }
        }
        if (orderList.isEmpty()) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.no_selected_goods));
            return;
        }
        Intent intent = new Intent(this, ConfirmGoodsOrderActivity.class);
        intent.putParcelableArrayListExtra(ActivityConstant.CONFIRM_GOODS_ORDER_LIST, orderList);
        startActivity(intent);
    }

    @OnClick(R.id.clear)
    public void clear() {
        if (adapter == null) {
            return;
        }
        List<Integer> shoppingCartList = new ArrayList<>();
        List<ShoppingCartModel> models = new ArrayList<>();
        for (ShoppingCartModel model : adapter.getShoppingCartList()) {
            if (model.isSelected()) {
                models.add(model);
            } else {
                List<ShoppingCartGoodsModel> goodsModels = new ArrayList<>();
                for (ShoppingCartGoodsModel m : model.getModels()) {
                    if (m.isSelected()) {
                        goodsModels.add(m);
                        shoppingCartList.add(m.getId());
                    }
                }
                model.getModels().removeAll(goodsModels);
                if (model.getModels().isEmpty()) {
                    models.add(model);
                }
            }
            model.setEditMode(false);
        }

        for (ShoppingCartModel model : models) {
            for (ShoppingCartGoodsModel m : model.getModels()) {
                shoppingCartList.add(m.getId());
            }
        }
        //网络删除列表
        deleteShoppingCart(shoppingCartList);
        //本地删除列表
        adapter.getShoppingCartList().removeAll(models);
        adapter.notifyDataSetChanged();
        selectAll.setChecked(false);
        LoadingDialogManager.getInstance().showLoadingDialog(this);

        //列表为空则隐藏底部栏
        hideBottomLayout(adapter.getItemCount() == 0);
    }


    /**
     * 是否进入编辑模式
     *
     * @param editMode true 进入编辑模式， false 编辑完成
     */
    private void editModeChange(boolean editMode) {
        if (editMode) {
            edit.setVisibility(View.GONE);
            complete.setVisibility(View.VISIBLE);
            balance.setVisibility(View.GONE);
            clear.setVisibility(View.VISIBLE);
            total.setVisibility(View.INVISIBLE);
            totalPrice.setVisibility(View.INVISIBLE);
        } else {
            edit.setVisibility(View.VISIBLE);
            complete.setVisibility(View.GONE);
            balance.setVisibility(View.VISIBLE);
            clear.setVisibility(View.GONE);
            total.setVisibility(View.VISIBLE);
            totalPrice.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏底部栏
     */
    private void hideBottomLayout(boolean hide) {
        bottomLayout.setVisibility(hide ? View.GONE : View.VISIBLE);
        refreshEmptyStatus(hide);
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        shoppingList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        shoppingList.setNestedScrollingEnabled(false);
    }

    /**
     * 获取购物车列表
     */
    private void getShoppingCart() {
        presenter.getShoppingCart();
    }

    /**
     * 修改购物车列表
     */
    private void modifyShoppingCart() {
        if (adapter == null || adapter.getItemCount() == 0) {
            return;
        }
        List<ModifyShoppingCartTask.Product> productList = new ArrayList<>();
        for (ShoppingCartModel model : adapter.getShoppingCartList()) {
            for (ShoppingCartGoodsModel m : model.getModels()) {
                ModifyShoppingCartTask.Product product = new ModifyShoppingCartTask.Product();
                product.count = m.getCount();
                product.shoppingCartId = m.getId();
                product.skuId = m.getSkuId();

                productList.add(product);
            }
        }
        presenter.modifyShoppingCart(productList);
    }

    /**
     * 删除购物车列表
     *
     * @param shoppingCartList 待删除列表
     */
    private void deleteShoppingCart(List<Integer> shoppingCartList) {
        presenter.deleteShoppingCart(shoppingCartList);
    }

    /**
     * 是否显示空提示
     *
     * @param show true:显示，false:不显示
     */
    private void refreshEmptyStatus(boolean show) {
        empty.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}
